package com.blackhorse.filters;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

/**
 * 自定义局部过滤器工厂类，局部过滤器只对配置的路由route生效
 * 1.名字以XXXXGatewayFilterFactory结尾 2.必须继承AbstractGatewayFilterFactory，泛型指定一个配置类
 */
@Slf4j
@Component
public class LogGatewayFilterFactory extends AbstractGatewayFilterFactory<LogGatewayFilterFactory.Config> {

    public LogGatewayFilterFactory() {
        super(LogGatewayFilterFactory.Config.class);
    }

    /**
     * 读取配置文件中的对应参数，赋值到配置类的属性中
     */
    @Override
    public List<String> shortcutFieldOrder() {
        //返回参数顺序必须与配置文件中顺序一致
        return Arrays.asList("consoleLog", "cacheLog");
    }

    /**
     * 过滤器逻辑
     */
    @Override
    public GatewayFilter apply(Config config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                if (config.isCacheLog()) {
                    log.info("cacheLog已经开启了...");
                }
                if (config.isConsoleLog()) {
                    log.info("isConsoleLog已经开启了...");
                }
                //将请求传递沿着过滤器链传递下去
                return chain.filter(exchange);
            }
        };
    }


    /**
     * 配置类，用于接收yml中配置参数
     */
    @Data
    public static class Config {
        private boolean consoleLog;
        private boolean cacheLog;
    }
}
